package utils;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.ddlutils.model.Column;
import org.apache.ddlutils.model.Database;
import org.apache.ddlutils.model.Table;

public class JsonHelper {

	public static void main(String[] args) {
		System.out.println(DBHelper.readDatabase());
	}

	public static DynaBean getDynaBeanFromJson(String json) {
		// JSONObject to DynaBean
		JSONObject jsonObject = JSONObject.fromObject(json);
		DynaBean bean = (DynaBean) JSONObject.toBean(jsonObject);
		return bean;
	}
	
	public static DynaBean getLazyDynaBeanFromJson(String json) {
		// JSONObject to DynaBean
		JSONObject jsonObject = JSONObject.fromObject(json);
		DynaBean bean = (DynaBean) JSONObject.toBean(jsonObject, LazyDynaBean.class);
		return bean;
	}

	public static Object getJsonFromBean(DynaBean bean) {
		JsonConfig config = getJsonDateConfig();
		// DynaBean to JSONObject
		JSONObject json = JSONObject.fromObject(bean, config);
		return json;
	}


	private static JsonConfig getJsonDateConfig() {
		// json-lib默认不支持java.sql.Date的序列化，要序列化自己的类，实现一个BeanProcessor处理即可
		JsonConfig config = new JsonConfig();
		config.registerJsonValueProcessor(Object.class, new JsonValueProcessor() {
			private final String format = "yyyy-MM-dd";

			public Object processObjectValue(String key, Object value, JsonConfig arg2) {
				return processBean(value, arg2);
			}

			@Override
			public Object processArrayValue(Object value, JsonConfig jsonConfig) {
				return processBean(value, jsonConfig);
			}

			public Object processBean( Object bean, JsonConfig jsonConfig ) {
				  Object jsonObject = null;
			      if( bean instanceof java.sql.Date ){
			         bean = new Date( ((java.sql.Date) bean).getTime() );
			      }
			      if( bean instanceof Date ){
			         jsonObject = new SimpleDateFormat(format).format((Date) bean);
			      }else{
			         jsonObject = bean;
			      }
			      return jsonObject;
			   }
		});
		return config;
	}

	public static void printDynaProperty(DynaBean bean) {
		DynaProperty[] dynaProperties = bean.getDynaClass().getDynaProperties();
		for (DynaProperty dynaProperty : dynaProperties) {
			System.out.println("dynaProperty.getType()= " + dynaProperty.getType());
			String propertyName = dynaProperty.getName();
			System.out.println(" " + propertyName + ":" + bean.get(propertyName));
		}
	}

}
